<<<<<<< HEAD
from django.shortcuts import render
from django.http import JsonResponse
from uuapp.models import *


def cart(request):
    return render(request, 'cart.html')


def show_cart(request):
    """
    Display shopping cart contents
    """
    cart = request.session.get('cart', {})
    cart_items = []
    
    # Get goods details for items in cart
    for goods_id, quantity in cart.items():
        try:
            goods = Goods.objects.get(id=goods_id)
            cart_items.append({
                'goods': goods,
                'quantity': quantity
            })
        except Goods.DoesNotExist:
            continue
    
    return render(request, 'show_cart.html', {'cart_items': cart_items})


def add_to_cart(request):
    """
    Add goods to shopping cart
    """
    goods_id = request.GET.get('id')
    quantity = int(request.GET.get('quantity', 1))
    
    if not goods_id:
        return JsonResponse({'status': 0, 'errmsg': '商品ID不能为空'}, status=400)
    
    try:
        goods = Goods.objects.get(id=goods_id)
    except Goods.DoesNotExist:
        return JsonResponse({'status': 0, 'errmsg': '商品不存在'}, status=404)
    
    # Initialize cart in session if not exists
=======
# from django.shortcuts import render
# from django.http import JsonResponse
# from uuapp.models import *
# cart/views.py
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, JsonResponse
from uuapp.models import User, StockOut, Product, StockIn, StockWarning, Order, ProductCategory, Purchase

from django.shortcuts import render, redirect
from django.http import JsonResponse
from .models import Cart, CartItem, Product  # 确保从正确的位置导入模型

def api_products(request):
    """
    API endpoint to return product data in JSON format
    """
    products = Product.objects.all().values('product_code', 'name', 'price')
    return JsonResponse(list(products), safe=False)
# cashier
def show_cart(request):
     from .models import ProductCategory, Product

def show_cart(request):
    categories = ProductCategory.objects.all()
    Product_list = Product.objects.filter(stock__gt=0)
    return render(request, 'show_cart.html', {'categories': categories, 'Product_list': Product_list})



# def view_cart(request):  # 重命名视图函数以避免冲突
#     return render(request, 'cart.html')

# def show_cart(request):
#     """
#     Display shopping cart contents
#     """
#     cart = request.session.get('cart', {})
#     cart_items = []
    
#     for goods_id, quantity in cart.items():
#         try:
#             goods = Product.objects.get(id=goods_id)  # 确保使用正确的模型名
#             cart_items.append({
#                 'goods': goods,
#                 'quantity': quantity
#             })
#         except Product.DoesNotExist:
#             continue
    
#     return render(request, 'show_cart.html', {'cart_items': cart_items})

# @login_required
def add_to_cart(request, product_id):
    product = get_object_or_404(Product, id=product_id)
    cart, created = Cart.objects.get_or_create(user=request.user)
    
    cart_item, created = CartItem.objects.get_or_create(
        cart=cart,
        product=product,
        defaults={'quantity': 1, 'price': product.price}
    )
    
    if not created:
        cart_item.quantity += 1
        cart_item.save()
    
    return redirect('product_detail', id=product_id)

# def cart(request):
#     return render(request, 'cart.html')


# def show_cart(request):
#     """
#     Display shopping cart contents
#     """
#     cart = request.session.get('cart', {})
#     cart_items = []
    
#     # Get goods details for items in cart
#     for goods_id, quantity in cart.items():
#         try:
#             goods = Goods.objects.get(id=goods_id)
#             cart_items.append({
#                 'goods': goods,
#                 'quantity': quantity
#             })
#         except Goods.DoesNotExist:
#             continue
    
#     return render(request, 'show_cart.html', {'cart_items': cart_items})

from django.shortcuts import render, get_object_or_404
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_POST
from .models import Product
import json

# 购物车主视图
@login_required
def show_cart(request):
    # 从 session 获取购物车数据
    cart = request.session.get('cart', {})
    cart_items = []
    subtotal = 0
    
    # 构建购物车商品列表
    for product_id, item_data in cart.items():
        try:
            product = Product.objects.get(product_code=product_id)
            quantity = item_data.get('quantity', 0)
            item_subtotal = product.price * quantity
            cart_items.append({
                'product': product,
                'quantity': quantity,
                'subtotal': item_subtotal
            })
            subtotal += item_subtotal
        except Product.DoesNotExist:
            continue  # 如果商品不存在，跳过
    
    context = {
        'cart_items': cart_items,
        'subtotal': "{:.2f}".format(subtotal),
    }
    return render(request, 'cart.html', context)

# AJAX 更新购物车
@require_POST
@login_required
def update_cart(request):
    try:
        data = json.loads(request.body)
        product_id = data.get('product_id')
        quantity = int(data.get('quantity', 1))
        
        # 获取产品
        product = get_object_or_404(Product, product_code=product_id)
        
        # 初始化购物车
        if 'cart' not in request.session:
            request.session['cart'] = {}
            
        cart = request.session['cart']
        
        if quantity > 0:
            # 更新商品数量
            if product_id in cart:
                cart[product_id]['quantity'] = quantity
            else:
                cart[product_id] = {
                    'quantity': quantity,
                    'name': product.name
                }
        else:
            # 移除商品
            if product_id in cart:
                del cart[product_id]
        
        request.session.modified = True
        
        # 计算新总计
        subtotal = 0
        for item_id, item_data in cart.items():
            try:
                product = Product.objects.get(product_code=item_id)
                subtotal += product.price * item_data['quantity']
            except Product.DoesNotExist:
                continue
        
        return JsonResponse({
            'success': True,
            'message': '购物车已更新',
            'subtotal': "{:.2f}".format(subtotal),
            'total': "{:.2f}".format(subtotal)  # 这里可以加入折扣计算
        })
        
    except Exception as e:
        return JsonResponse({
            'success': False,
            'message': str(e)
        }, status=400)

# 添加到购物车
@login_required
def add_to_cart(request, product_id):
    product = get_object_or_404(Product, product_code=product_id)
    
    # 初始化购物车
>>>>>>> 0ac75087e5e07a3ef0624f7a4a9866c7346941b7
    if 'cart' not in request.session:
        request.session['cart'] = {}
    
    cart = request.session['cart']
    
<<<<<<< HEAD
    # Add or update goods in cart
    if goods_id in cart:
        cart[goods_id] += quantity
    else:
        cart[goods_id] = quantity
    
    # Save cart to session
    request.session.modified = True
    
    return JsonResponse({'status': 1, 'msg': '添加成功'})
=======
    # 添加或增加商品数量
    if product_id in cart:
        cart[product_id]['quantity'] += 1
    else:
        cart[product_id] = {
            'quantity': 1,
            'name': product.name
        }
    
    request.session.modified = True
    
    # 重定向到购物车页面或来源页面
    return redirect(request.META.get('HTTP_REFERER', 'cart:show_cart'))

# 从购物车移除
@login_required
def remove_from_cart(request, product_id):
    if 'cart' in request.session and product_id in request.session['cart']:
        del request.session['cart'][product_id]
        request.session.modified = True
    
    return redirect('cart:show_cart')
>>>>>>> 0ac75087e5e07a3ef0624f7a4a9866c7346941b7
